package com.lastoffer2;

import java.util.ArrayList;
import java.util.List;

import com.lastct.dao.Offer;
import com.lastoffer2.adapter.AdapterMenuPrincipale;
import com.lastoffer2.adapter.ImagePagerAdapter;
import com.lastoffer2.listener.OnItemClickListenerMainMenu;
import com.lastoffer2.util.JSONConnector;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;

public class MainMenuActivity extends Activity {

	public List<Offer> data = new ArrayList<Offer>();
	private ProgressDialog pd;
	private ImagePagerAdapter adapterGallery;
	private ViewPager mPager;
	private ListView listView;
	private AdapterMenuPrincipale adapterListView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_menu);

		if (savedInstanceState != null) {
			data = (ArrayList<Offer>) savedInstanceState
					.getSerializable("data");
		}
		adapterGallery = new ImagePagerAdapter(data, this);
		adapterListView = new AdapterMenuPrincipale(this);
		mPager = (ViewPager) findViewById(R.id.galleriaOfferte);
		listView = (ListView) findViewById(R.id.listViewMenuPrincipale);
		listView.setAdapter(adapterListView);
		listView.setOnItemClickListener(new OnItemClickListenerMainMenu(this));
		mPager.setAdapter(adapterGallery);

 
		
		if (data.isEmpty()) {
			// Start a new thread that will download all the data
			new DownloadTask()
					.execute("Any parameters my download task needs here");
			this.pd = ProgressDialog.show(this, "Working..",
					"Downloading Data...", true, false);
		}

	}

	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
		super.onSaveInstanceState(savedInstanceState);

		savedInstanceState.putSerializable("data", new ArrayList<Offer>(data));
		savedInstanceState.putLong("time", System.currentTimeMillis());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main_menu, menu);
		return true;
	}

	private class DownloadTask extends AsyncTask<String, Void, Object> {

		protected Object doInBackground(String... args) {
			Log.i("LastOffer", "Background thread starting");
			List<Offer> result = JSONConnector.getListOfferByUserId(new Integer(-1));

			return result;
		}

		protected void onPostExecute(Object result) {
			// Pass the result data back to the main activity
			MainMenuActivity.this.data = (List<Offer>) result;
			MainMenuActivity.this.adapterGallery.data = MainMenuActivity.this.data;
			MainMenuActivity.this.adapterGallery.notifyDataSetChanged();
			if (MainMenuActivity.this.pd != null) {
				MainMenuActivity.this.pd.dismiss();
			}
		}

	}

}
